<template>
  <div>
    <el-form ref="deptForm" :model="form" :rules="rules" label-width="120px">
      <el-form-item label="部门名称" prop="name">
        <el-input v-model="form.name" style="width:80%" placeholder="1-50个字符" />
      </el-form-item>
      <el-form-item label="部门编码" prop="code">
        <el-input v-model="form.code" style="width:80%" placeholder="1-50个字符" />
      </el-form-item>
      <el-form-item label="部门负责人" prop="manager">
        <el-select v-model="form.manager" style="width:80%" placeholder="请选择">
          <el-option v-for="item in employees" :key="item.id" :value="item.username" :label="item.username" />
        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍" prop="introduce">
        <el-input v-model="form.introduce" style="width:80%" placeholder="1-300个字符" type="textarea" :rows="3" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="small" @click="hSubmit">确定</el-button>
        <el-button size="small" @click="hCancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { getEmployeeSimple, addDepartements, getDepartmentDetail, updataDepartmentDetail } from '@/api/employees.js'

export default {
  props: {
    curId: {
      type: String,
      required: true
    },
    idEdit: {
      type: Boolean,
      required: true
    },
    originList: {
      type: Array,
      required: true
    }
  },
  data() {
    // 自定义部门编码的校验
    const validCode = (rule, value, callback) => {
      // value:当前表单项值
      let exsiCodeList = this.originList.map(item => item.code)
      if (this.idEdit) {
        exsiCodeList = this.originList.filter(item => item.id !== this.curId).map(item => item.code)
      }
      if (exsiCodeList.includes(value)) {
        // 存在
        callback(new Error(`部门编码${value}已存在`))
      } else {
        // 不存在
        callback()
      }
    }
    // 自定义部门编码的名称
    const validName = (rule, value, callback) => {
      // value:当前表单项值
      let exsiCodeList = this.originList.filter(item => item.id === this.curId).map(item => item.name)
      if (this.isEdit) {
        // 1.找到当前编辑部门的对象   find===>第一个找到对象
        const curDepartment = this.originList.find(item => item.id === this.curId)
        // 2.获取当前编辑对象的pid
        const pid = curDepartment.pid
        // 3.构建已储存的数据列表 找到所有的兄弟 (包括了自己) 存在列表= 兄弟 - 自己
        exsiCodeList = this.originList.filter(item => item.pid === pid && item.id !== this.curId).map(item => item.name)
      }
      exsiCodeList.includes(value) ? callback(new Error(`部门名称${value}已存在`)) : callback()
    }

    return {
      form: {
        name: '',
        code: '',
        manager: '',
        introduce: ''
      },
      employees: [],
      rules: {
        name: [
          { required: true, message: '部门名称不能为空', trigger: 'blur' },
          { min: 1, max: 50, message: '部门名称要求1-50个字符', trigger: 'blur' },
          { validator: validName, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '部门编码不能为空', trigger: 'blur' },
          { min: 1, max: 50, message: '部门编码要求1-50个字符', trigger: 'blur' },
          { validator: validCode, trigger: 'blur' }
        ],
        manager: [
          { required: true, message: '部门负责人不能为空', trigger: 'blur' }
        ],
        introduce: [
          { required: true, message: '部门介绍不能为空', trigger: 'blur' },
          { min: 1, max: 300, message: '部门介绍要求1-300个字符', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.loadEmployees()
    if (this.idEdit) {
      this.loadDepartmentDeatail()
    }
  },
  methods: {
    resetForm() {
      // 重置表单
      this.$refs.deptForm.resetFields()
    },
    // 获取部门负责人
    async loadEmployees() {
      try {
        const { data: res } = await getEmployeeSimple()
        // console.log(res, 'loadEmployees')
        this.employees = res
      } catch (error) {
        console.log(error)
      }
    },
    // 通过id查询对应部门
    async loadDepartmentDeatail() {
      try {
        const { data: res } = await getDepartmentDetail(this.curId)
        // console.log(res, 'getDepartmentDetail')
        this.form = res
      } catch (error) {
        console.log(error)
      }
    },
    // 编辑部门
    async doEdit() {
      try {
        await updataDepartmentDetail(this.form)
        // console.log(res, '编辑部门')
        // 刷新页面
        this.$emit('success')
      } catch (error) {
        console.log(error)
      }
    },
    // 新增子部门
    async doAdd() {
      try {
        await addDepartements({ pid: this.curId, ...this.form })
        // console.log(res, '新增部门')
        this.$emit('success')
      } catch (error) {
        console.log(error)
      }
    },
    // 确定
    hSubmit() {
      this.$refs.deptForm.validate(valid => {
        if (!valid) return // 校验失败
        // 新增获取编辑
        this.isEdit ? this.doEdit() : this.doAdd()
      })
    },
    // 取消
    hCancel() {
      this.$emit('close')
    }
  }
}
</script>

<style>

</style>
